#!/usr/bin/python3
# -*- coding: utf8 -*-
# Date   : 2021/02/12
# Author : Kwan
# Email  : allenxian@live.com
# Blog   : https://my.oschina.net/u/4173440

from flask import Blueprint, request, json, abort
from flask_login import current_user, login_required
from project.define import page_logger, AxiosMessage
from project.prepare import CarParkService


# 接口功能
interface = Blueprint(name='interface', import_name='project', url_prefix='/interface')
RouterName = "interface"
PageMessage = AxiosMessage()


@interface.route('/system', methods=['POST'])
@login_required
def system():
    """
    系统接口
    """
    view = "system"
    try:
        # 检查数据类型
        p_data = request.get_json()
        if not isinstance(p_data, dict):
            p_data = json.loads(p_data)
        page_logger.debug(f"{RouterName}.{view} 接口数据：{current_user.LoginName} => {p_data}")
        cb = p_data.get('CallBack')
        if cb:
            if cb == "Restart":
                return PageMessage.warning("服務即將重啓，請稍後重新登入系統！")
            elif cb == 'Reboot':
                return PageMessage.warning("系統即將重啓，請等待系統重新啓動！")
            elif cb == 'Halt':
                return PageMessage.warning("系統即將關閉，服務將不可用！")
            elif cb == 'Debug':
                CarParkService.debug_switch()
                if CarParkService.Debug:
                    msg = "出入演示開始！"
                else:
                    msg = "出入演示暫停！"
                return PageMessage.success(msg)
    except Exception as e:
        page_logger.error(f"{RouterName}.{view} 解析数据错误：{p_data}，原因：{e}")
    return abort(500)


@interface.route('/user_info', methods=['POST'])
@login_required
def user_info():
    """
    当前用户接口
    """
    view = "user_info"
    try:
        # 检查数据类型
        p_data = request.get_json()
        if not isinstance(p_data, dict):
            p_data = json.loads(p_data)
        page_logger.debug(f"{RouterName}.{view} 接口数据：{current_user.LoginName} => {p_data}")
        cb = p_data.get('UpdateUser')
        if cb:
            return PageMessage.success("用戶更新成功！")
    except Exception as e:
        page_logger.error(f"{RouterName}.{view} 解析数据错误：{p_data}，原因：{e}")
    return abort(500)

